<?php

namespace Illuminate\Container;

use Illuminate\Contracts\Container\Container;
use Illuminate\Contracts\Container\ContextualBindingBuilder as ContextualBindingBuilderContract;

/**
 * 上下文服务构建器
 */
class ContextualBindingBuilder implements ContextualBindingBuilderContract
{
    /**
     * 底层容器实例
     *
     * @var \Illuminate\Contracts\Container\Container
     */
    protected $container;

    /**
     * 上下文类
     *
     * @var string|array
     */
    protected $concrete;

    /**
     * 上下文类绑定的抽象目标
     *
     * @var string
     */
    protected $needs;

    /**
     * 创建一个上下文服务构建器
     *
     * @param  \Illuminate\Contracts\Container\Container $container
     * @param  string|array $concrete
     * @return void
     */
    public function __construct(Container $container, $concrete)
    {
        $this->concrete = $concrete;
        $this->container = $container;
    }

    /**
     * 定义上下文类要绑定的抽象目标
     *
     * @param  string $abstract
     * @return $this
     */
    public function needs($abstract)
    {
        $this->needs = $abstract;

        return $this;
    }

    /**
     * 定义上下文类要绑定的实现
     *
     * @param  \Closure|string $implementation
     * @return void
     */
    public function give($implementation)
    {
        foreach (Util::arrayWrap($this->concrete) as $concrete) {
            $this->container->addContextualBinding($concrete, $this->needs, $implementation);
        }
    }
}
